﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using DAL.Models;
using DAL.BAL;
using WpfClient.Classes;
using System.Net.Mail;

namespace WpfClient.Windows
{
    /// <summary>
    /// Interaction logic for Find_Candidates.xaml
    /// </summary>
    public partial class Sent_Candidates_WthEml : Window
    {
        private Vacancy vacancy = null;

        Dictionary<int, bool> selectedValues = new Dictionary<int, bool>();

        public Sent_Candidates_WthEml(Vacancy vacancy)
        {
            InitializeComponent();

            this.vacancy = vacancy;

            if ((Business.currentUser.EMail == null) || (Business.currentUser.EMail == string.Empty))
                bSend.IsEnabled = false;

            Refresh();
        }

        private void gridControl1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Candidate candidate = (Candidate)gridControl1.GetFocusedRow();

            if (candidate != null)
                new CandidateEdit(candidate, false, false).ShowDialog();
        }

        private void Refresh()
        {
            Business.Refresh(System.Data.Objects.RefreshMode.ClientWins, Business.MyEntities.Candidates);

            gridControl1.ItemsSource = Business.GetCandidatesForVacancy(vacancy);
        }

        private void RefreshItem_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Refresh();
        }

        private void gridControl1_CustomUnboundColumnData(object sender, DevExpress.Xpf.Grid.GridColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "Selected")
            {
                int key = (int)e.GetListSourceFieldValue("Id");
                if (e.IsGetData)
                {
                    e.Value = GetIsSelected(key);
                }
                if (e.IsSetData)
                {
                    SetIsSelected(key, (bool)e.Value);
                }
            }
            else
                if (e.Column.FieldName == "Positions")
                {
                    int key = (int)e.GetListSourceFieldValue("Id");

                    if (e.IsGetData)
                    {
                        string _positions = string.Empty;

                        var p = from n in Business.dosvidEntities.Candidate_Positions
                                where n.CandidateId == key
                                select n;

                        foreach (Candidate_Positions cp in p)
                        {
                            _positions += string.Format("{0};", cp.Position.PositionName);
                        }

                        e.Value = _positions;
                    }
                }
                else
                    if (e.Column.FieldName == "RangeTerritory")
                    {
                        int key = (int)e.GetListSourceFieldValue("Id");

                        if (e.IsGetData)
                        {
                            string _rangeTerritory = string.Empty;

                            var p = from n in Business.dosvidEntities.Candidat_RangeTerritories
                                    where n.CandidateId == key
                                    select n;

                            foreach (Candidat_RangeTerritories cp in p)
                            {
                                _rangeTerritory += string.Format("{0};", cp.Territory.TerritoryName);
                            }

                            e.Value = _rangeTerritory;
                        }
                    }
                    else
                        if (e.Column.FieldName == "WholeExpirience")
                        {
                            int key = (int)e.GetListSourceFieldValue("Id");

                            if (e.IsGetData)
                            {
                                decimal sum = 0;

                                var p = from n in Business.dosvidEntities.Candidat_Expiriences
                                        where n.CandidatID == key
                                        select n;

                                foreach (Candidat_Expiriences ce in p)
                                {
                                    sum += ce.Years;
                                }

                                e.Value = sum.ToString();
                            }
                        }
        }

        private bool GetIsSelected(int key)
        {
            bool isSelected;
            if (selectedValues.TryGetValue(key, out isSelected))
                return isSelected;
            return false;
        }

        private void SetIsSelected(int key, bool value)
        {
            if (value)
                selectedValues[key] = value;
            else
                selectedValues.Remove(key);
        }

        private void bClose_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void bSend_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            if (vacancy.Candidate == null)
            {
                MessageBox.Show(WpfClient.Properties.Resources.CanNotSendEMail, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                
                return;
            }

            foreach (int key in selectedValues.Keys)
            {
                Candidate candidate = (from n in Business.GetCandidates()
                                       where n.Id == key && n.Candidat_EMails != null
                                       //  where n.Id == keywhere n.Id == key
                                       select n).FirstOrDefault();

                if (candidate != null)
                {
                    #region create Send Mail

                    SendEmail sendEmail = new SendEmail();

                    sendEmail.SMTPAdress = Business.currentUser.EMail_SMTP_Server;

                    sendEmail.Password = Business.currentUser.EMail_Password;

                    sendEmail.UserName = Business.currentUser.Emil_UserName;

                    #endregion

                    MailMessage message = null;

                    try
                    {
                            message = EmailMessage.CreateMessageforCandidate(vacancy, candidate);
                            if (message != null)
                            {
                                bool isSimilarEmail = false;

                                foreach (MailAddress email in message.To)
                                {
                                    var emails = from n in candidate.SentEmailsHistories
                                                 where n.EMail == email.ToString()
                                                 select n;
                                    if (emails.Count() > 0)
                                    {
                                        isSimilarEmail = true;
                                        break;
                                    }
                                }

                                if (isSimilarEmail)
                                    if (MessageBox.Show(string.Format("Резюме вакансии {0} уже было отправлено на один из адресов етого роботодателя. Хотите отправить повторно ?", candidate.LastName), WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
                                        break;
                                
                                sendEmail.Message = message;

                                sendEmail.Send();

                                sendEmail.Dispose();

                                #region Save result to DB 
                                /*
                                Candidat_VacancyHistory cvh = new Candidat_VacancyHistory();

                                cvh.Candidate = candidate;

                                cvh.VacancyId = this.vacancy.Id;

                                cvh.SendResumeDate = DateTime.Today;

                                cvh.IsAutoAdded = true;

                                vacancy.Candidat_VacancyHistory.Add(cvh);

                                foreach (MailAddress email in message.To)
                                {
                                    SentEmailsHistory seh = new SentEmailsHistory();

                                    seh.Candidate = candidate;

                                    seh.SendDate = DateTime.Now.Date;

                                    seh.EMail = email.ToString();

                                    seh.IsContactInfoAttached = false;

                                    seh.VacancyId = vacancy.Id;

                                    candidate.SentEmailsHistories.Add(seh);

                                }

                                Business.Save();
                                */
                                #endregion

                                MessageBox.Show(WpfClient.Properties.Resources.MessageWasSent, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Information);


                            }
                        
                    }
                     catch (Exception e1)
                    {
                        MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    finally
                    {
                        if (message != null)
                        {
                            string fileForDelete = string.Empty;

                            if (message.Attachments.FirstOrDefault() != null)
                                fileForDelete = message.Attachments.FirstOrDefault().Name;

                            message.Dispose();

                            EmailMessage.DeleteFile(fileForDelete);
                        }
                    }
                }
            }
        }
    }

}
